from django import forms
from django.core.exceptions import ValidationError
from web import models
from utils import encrypt

class PasswordChangeForm(forms.ModelForm):
    old_password = forms.CharField(
        label='旧密码',
        min_length=6,
        max_length=16,
        error_messages={'min_length': '密码长度不能小于6位', 'max_length': '密码长度不能大于16位'},
        widget=forms.PasswordInput()
    )
    new_password = forms.CharField(
        label='新密码',
        min_length=6,
        max_length=16,
        error_messages={'min_length': '密码长度不能小于6位', 'max_length': '密码长度不能大于16位'},
        widget=forms.PasswordInput()
    )
    confirm_password = forms.CharField(
        label="确认新密码",
        min_length=6,
        max_length=16,
        error_messages={'min_length': '密码长度不能小于6位', 'max_length': '密码长度不能大于16位'},
        widget=forms.PasswordInput()
    )

    class Meta:
        model = models.UserInfo
        fields = ['old_password', 'new_password', 'confirm_password']

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user

    def clean_old_password(self):
        old_password = self.cleaned_data.get('old_password')
        # 检查旧密码是否正确
        if encrypt.md5(old_password) != self.user.password:
            raise ValidationError('旧密码错误')
        return old_password

    def clean(self):
        cleaned_data = super().clean()
        new_password = cleaned_data.get('new_password')
        confirm_password = cleaned_data.get('confirm_password')

        # 检查新密码和确认新密码是否一致
        if new_password and confirm_password and new_password != confirm_password:
            self.add_error('confirm_password', '新密码和确认新密码不一致')

        return cleaned_data

    def save(self, commit=True):
        self.user.password = encrypt.md5(self.cleaned_data['new_password'])
        if commit:
            self.user.save()
        return self.user
